from flask import Blueprint, jsonify, request
from models import  db,  Message
message_api = Blueprint('message_api', __name__)


# 添加留言
@message_api.route('/add_message', methods=['POST'])
def add_message():
	data = request.get_json()
	
	message = Message(**data)
	db.session.add(message)
	db.session.commit()
	result = {
		'message': '留言成功！',
		'code': 200
	}
	return jsonify(result)


# 查看留言
@message_api.route('/get_message', methods=['GET'])
def get_message():
	# 获取查询参数
	to_user_id = request.args.get('to_user_id', type=int)
	type = request.args.get('type', type=int)
	message_list = Message.query.filter(Message.to_user_id == to_user_id, Message.type == type).all()
	message_list_json = [
		{
			'id': message.id,
			'from_user': message.from_user,
			'from_user_id': message.from_user_id,
			'to_user': message.to_user,
			'to_user_id': message.to_user_id,
			'message': message.message,
			'type': message.type,
			'create_time': message.create_time.strftime('%Y-%m-%d %H:%M:%S')
		}
		for message in message_list
	]
	
	data = {
		'code': 200,
		'data': message_list_json
	}
	return jsonify(data)